<template>
  <div id="map"></div>
  <button class="back" @click="goBack" v-show="isShowBack">返回</button>
</template>
  
<script setup>
import { ref, onMounted, computed } from 'vue';
import * as echarts from 'echarts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent, VisualMapComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { use } from 'echarts/core';

// 注册 ECharts 组件
use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
  CanvasRenderer,
]);

// 示例数据
const dataList = ref([
  {
    code: 610000,
    industryList: [
      { count: 1, label: '金融' },
      { count: 1, label: '互联网' },
    ],
  },
  {
    code: 620000,
    industryList: [
      { count: 1, label: '金融' },
      { count: 1, label: '互联网' },
      { count: 2, label: '政务' },
    ],
  },
  {
    code: 110000,
    industryList: [
      { count: 1, label: '互联网' },
    ],
  },
]);

// 用于缓存已经加载的地图数据，避免重复加载
const mapList = ref([]);

// 当前地图名称
const currentMapName = ref('100000_full');

// 当前高亮的省份索引
const currentHighlightIndex = ref(0); 

const isShowBack = computed(() => {
  // 当 mapList 中有数据时返回 true，反之返回 false
  return mapList.value.length !== 0;
});

// 使用线上API获取地图数据
const getMapJson = async (mapName) => {
  try {
    const url = `https://geo.datav.aliyun.com/areas_v3/bound/${mapName}.json`;
    const mapJson = await fetch(url).then(res => res.json());
    return mapJson;
  } catch (error) {
    console.error('地图数据加载失败', error);
    alert('地图数据加载失败');
    return null;
  }
};

// ECharts 实例
const chart = ref(null);

// 设置ECharts的配置项
const setOptions = (mapName, mapData, scatterData, isDrilledDown) => {
  const layoutCenter = isDrilledDown ? ['50%', '50%'] : ['50%', '70%'];
  const layoutSize = isDrilledDown ? '100%' : '150%';
  // 获取当前高亮的省份
  const highlightedProvinceCode = dataList.value[currentHighlightIndex.value]?.code;
  // console.log(highlightedProvinceCode);
  return {
    tooltip: {
      show: true,
      formatter: function (params) {
        if (params && params.data) {
          const { adcode, name, industryList } = params.data;
          const industries = industryList.map(industry => `${industry.label}: ${industry.count}`).join('<br>');
          return `${industries}`;
        }
      },
    },
    // 左下角的数据颜色条 映射地图颜色
    visualMap: {
      show: false,
      min: 0,
      max: 1,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'], // 文本，默认为数值文本
      calculable: true,
      seriesIndex: [0],// index 层级
      inRange: {
        color: ['#eef9ff', '#40acfc'] // 蓝绿#00467f #40acfc
      },
      outOfRange: {
        color: ['#FF0000']
      },
      // controller: {
      //   inRange: {
      //     color: ['#ffffff', '#A5CC82']
      //   },
      //   outOfRange: {
      //     color: ['#FF0000']
      //   }
      // }
    },
    geo: {
      map: mapName,
      roam: true,
      layoutCenter,
      layoutSize,
      label: {
        show: true
      },
      emphasis: {
        // :hover效果
        itemStyle: {
          areaColor: '#e7b273',
          borderColor: '#e7b273',
          borderWidth: 0
        },
        label: {
          fontSize: 14,
        },
      }
    },
    series: [
      // 数据
      {
        type: 'map',
        map: mapName,
        roam: true,
        geoIndex: 0,
        select: false,
        data: mapData.map(item => {
          if (item.adcode === highlightedProvinceCode) {
            return {
              ...item,
              itemStyle: {
                color: '#FFCC00' // 设置高亮省份的颜色
              }
            };
          }
          return item;
        }),
      },
      // 散点
      {
        name: '散点',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: mapData,
        itemStyle: {
          color: '#05C3F9'
        }
      },
      // 气泡点
      {
        name: '点',
        type: 'scatter',
        coordinateSystem: 'geo',
        symbol: 'pin', //气泡
        symbolSize: function (val) {
          if (val) {
            return val[2] / 4 + 40; // 点大小
          }
        },
        label: {
          show: true,
          formatter: function (params) {
            return params.data.industryList.length || 0; // 点信息
          },
          color: '#fff',
          fontSize: 9,
        },
        itemStyle: {
          color: '#F62157', //标志颜色
        },
        zlevel: 6,
        data: scatterData,
      },
      {
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: scatterData,
        symbolSize: 15,
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke'
        },
        label: {
          formatter: '{b}',
          position: 'right',
          show: true
        },
        itemStyle: {
          color: 'yellow',
          shadowBlur: 10,
          shadowColor: 'yellow'
        },
        zlevel: 1,
      },
    ],
  };
};

// 渲染地图
const renderMapEcharts = async (mapName, isDrilledDown = false) => {
  const mapJson = await getMapJson(mapName);
  if (!mapJson) return; // 如果加载失败则返回
  // 注册地图数据
  echarts.registerMap(mapName, mapJson);
  // 处理地图数据，生成用于 ECharts 的数据格式
  const mapData = mapJson.features.map((item) => {
    const matchingData = dataList.value.find(data => data.code === item.properties.adcode);
    const industryList = matchingData ? matchingData.industryList : [];
    // 根据实际情况计算 value，这里简单计数 industryList 中的项目数量
    const value = industryList.reduce((sum, industry) => sum + industry.count, 0);
    return {
      name: item.properties.name,
      value, // 映射到 visualMap 的值
      adcode: item.properties.adcode, // 区域编码
      level: item.properties.level, // 层级
      industryList, // 行业列表
    };
  });

  // 处理标点数据
  const scatterData = dataList.value.map((item) => {
    const mapFeature = mapJson.features.find(feature => feature.properties.adcode === item.code);
    return {
      name: mapFeature ? mapFeature.properties.name : '',
      value: mapFeature ? mapFeature.properties.center.concat(item.industryList.length) : [0, 0, 0],
      industryList: item.industryList,
      adcode: item.code,
    };
  });

  // 设置图表配置项
  const options = setOptions(mapName, mapData, scatterData, isDrilledDown);
  // 渲染图表
  chart.value.setOption(options, true);

  // 获取当前高亮的省份 设置tooltip
  if (!isDrilledDown) {
    const highlightedProvinceCode = dataList.value[currentHighlightIndex.value]?.code;
    if (highlightedProvinceCode) {
      const provinceDataIndex = mapData.findIndex(item => item.adcode === highlightedProvinceCode);
      if (provinceDataIndex >= 0) {
        chart.value.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: provinceDataIndex,
        });
      }
    }
  }

};

// 监听图表点击事件
const handleChartClick = async (param) => {
  if (param.seriesType !== 'map') return;
  const { adcode, level } = param.data;
  // const mapName = level === 'district' ? adcode : adcode + '_full';
  if (level !== 'province') return; // 只允许从国家地图下钻到省级地图
  const mapName = `${adcode}_full`;
  currentMapName.value = mapName;
  if (mapList.value[mapList.value.length - 1] === mapName) {
    return alert('已经是最下层了');
  }
  dataList.value = [
    {
      code: 610100,
      industryList: [
        { count: 1, label: '互联网' },
      ],
    },
    {
      code: 610200,
      industryList: [
        { count: 1, label: '金融' },
        { count: 1, label: '互联网' },
        { count: 2, label: '政务' },
      ],
    },
    {
      code: 610300,
      industryList: [
        { count: 1, label: '互联网' },
      ],
    },
  ];
  mapList.value.push(mapName);
  await renderMapEcharts(mapName, true);
};

// 返回上一级地图
const goBack = async () => {
  const mapName = mapList.value[mapList.value.length - 2] || '100000_full';
  currentMapName.value = '100000_full';
  mapList.value.pop();
  dataList.value = [
    {
      code: 610000,
      industryList: [
        { count: 1, label: '金融' },
        { count: 1, label: '互联网' },
      ],
    },
    {
      code: 620000,
      industryList: [
        { count: 1, label: '金融' },
        { count: 1, label: '互联网' },
        { count: 2, label: '政务' },
      ],
    },
    {
      code: 110000,
      industryList: [
        { count: 1, label: '互联网' },
      ],
    },
  ]
  // await renderMapEcharts(mapName, mapName !== '100000_full');
  await renderMapEcharts('100000_full');
};

// 轮询高亮省份
const highlightProvince = () => {
  setInterval( async () => {
    if (currentMapName.value === '100000_full') {
      // 更新高亮的省份索引
      currentHighlightIndex.value = (currentHighlightIndex.value + 1) % dataList.value.length;
      // 重新渲染地图
      await renderMapEcharts('100000_full');
    }
  }, 5000); // 每10秒切换一次
};

// Vue 组件挂载时初始化图表
onMounted(async() => {
  // 获取数据
  // await Promise.all([
  //   getPanelData(),
  //   getProjectData({ regionLevel: 1 })
  // ]);
  // 初始化 ECharts 实例
  chart.value = echarts.init(document.getElementById('map'));
  // 渲染初始地图
  await renderMapEcharts('100000_full');
  // 添加点击事件监听
  chart.value.on('click', handleChartClick);
  // 重绘地图设置省份轮询高亮
  highlightProvince();
});


</script>

<style scoped>
#map {
  width: 100%;
  height: 100vh;
}

.back {
  width: 55px;
  height: 30px;
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>
  